package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.config.DfsProperties;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.lewin.movie.entity.PlayRole;
import la.iok.hzsvn.lewin.movie.entity.PlayRoleFile;
import la.iok.hzsvn.lewin.movie.entity.PlayRoleInstance;
import la.iok.hzsvn.lewin.movie.mapper.PlayRoleFileMapper;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.annotations.Nullable;
import la.iok.hzsvn.share.dfs.model.DfsDescriptor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class PlayRoleFileServiceImpl extends MovieFileServiceImpl<PlayRoleFile, PlayRoleFileMapper> implements PlayRoleFileService {
    public PlayRoleFileServiceImpl(PlayRoleFileMapper mapper, WebDfsService webDfsService, DfsProperties dfsProperties) {
        super(mapper, webDfsService, dfsProperties);
    }

    @Override
    public void downloadFile(@NotNull HttpServletResponse response, @Nullable Long fileId, @NotNull String playRoleName) {
        PlayRoleFile file = select(fileId);
        ErrorCode.PLAY_ROLE_FILE_NOT_EXIST.assertNotNull(file,playRoleName);
        DfsDescriptor descriptor = webDfsService.dfsFile(file.getPath());
        ErrorCode.PLAY_ROLE_FILE_NOT_EXIST.assertTrue(webDfsService.exist(descriptor),playRoleName);
        webDfsService.downloadFile(response,descriptor,file.getFileName());
    }

    @Override
    protected void validateReference(@NotNull PlayRoleFile file) {
        PlayRoleInstance item = executeSelect(PlayRoleInstance.class,"select * from "
                + PlayRoleInstance.class.getSimpleName() + " where fileDeleted=0 and fileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item,file.getPath(),PlayRoleInstance.class.getSimpleName());

        PlayRole item2 = executeSelect(PlayRole.class,"select * from "
                + PlayRole.class.getSimpleName() + " where fileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item2,file.getPath(),PlayRole.class.getSimpleName());
    }
}
